## ----measure-buffer-density----

load("replication_file_04_friendship_graph.RData")
load("replication_file_06_recruitment_graph.RData")

library(parallel)
library(data.table)
library(igraph)
library(sp)
library(sf)
library(rgdal)
library(dplyr)
library(DBI)
library(RSQLite)

# Functions
sqliteGetTable <- function(database, table) {
  require(DBI)
  require(RSQLite)
  con <- dbConnect(RSQLite::SQLite(), dbname = database)
  query <- dbSendQuery(con, paste("SELECT * FROM ", table, ";", sep="")) 
  result <- fetch(query, n = -1)
  dbClearResult(query)
  dbDisconnect(con)
  return(result)
}

region_2013.sp <- readOGR('.', 'Reg01012013_g_WGS84')
region_2013.sp <- 
  spTransform(region_2013.sp, "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
region_2013.sp$COD_REG <- as.numeric(as.character(region_2013.sp$COD_REG))

region_2013.sf <- st_as_sf(region_2013.sp)
region_south_2013.sf <- region_2013.sf %>% filter(COD_REG >= 13)

lonlat_node_df <- data.frame(lon = V(g_recruitment)$lon,
                             lat = V(g_recruitment)$lat)
lonlat_node.sp <- 
  SpatialPoints(lonlat_node_df,
                proj4string=CRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'))
res <- over(lonlat_node.sp, region_2013.sp)

V(g_recruitment)$DEN_REG <- as.character(res$DEN_REG)
V(g_recruitment)$COD_REG <- res$COD_REG
V(g_recruitment)$north_south <- ifelse(V(g_recruitment)$COD_REG < 13, "North", "South")

# Italy only
g_recruitment <- 
  g_recruitment - V(g_recruitment)[is.na(V(g_recruitment)$north_south)]

g_pnts <- 
  SpatialPointsDataFrame(cbind(V(g_recruitment)$lon, 
                               V(g_recruitment)$lat),
                         proj4string = CRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'),
                         data = data.frame(joined_mu = V(g_recruitment)$joined_mu,
                                           name = as.character(V(g_recruitment)$name)))
g_pnts <- spTransform(g_pnts, CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"))

meetup_members <- sqliteGetTable('meetup_mar15.sqlite', 'member')
italy_box_y <- c(36, 47.5)
italy_box_x <- c(6.1, 19.5)
meetup_members <- meetup_members[meetup_members$lon >= italy_box_x[1] & 
                                   meetup_members$lon <= italy_box_x[2] &
                                   meetup_members$lat >= italy_box_y[1] & 
                                   meetup_members$lat <= italy_box_y[2],]
mu_pnts <- 
  SpatialPoints(cbind(meetup_members$lon, 
                      meetup_members$lat),
                proj4string = CRS('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'))
mu_pnts <- 
  spTransform(mu_pnts, CRS("+proj=utm +zone=32 +datum=WGS84 +units=m +no_defs"))

countGeoActive <- function(i) {
  this_buff <- rgeos::gBuffer(g_pnts[i,], width = 20000)
  these_pre_pnts <- 
    g_pnts[as.POSIXct(g_pnts$joined_mu) < as.POSIXct(g_pnts$joined_mu[i]),]
  if (nrow(these_pre_pnts) == 0) {
    pre_active_buff_20km <- 0
  } else {
    pre_res <- over(these_pre_pnts, this_buff)
    pre_active_buff_20km <- sum(!is.na(pre_res))
  } 
  tot_res <- over(mu_pnts, this_buff)
  return(list(pre_active_buff_20km = pre_active_buff_20km, 
              tot_active_buff_20km = sum(!is.na(tot_res)),
              name = g_pnts$name[i]))
}

no_cores <- detectCores() - 1
cl <- makeCluster(no_cores, type="FORK")
 
res <- parLapply(cl, 1:vcount(g_recruitment), countGeoActive)
net_active_buff_20km_df <- 
  data.frame(name = sapply(res, FUN = function(x) x$name),
             pre_active_buff_20km = sapply(res, FUN = function(x) x$pre_active_buff_20km),
             tot_active_buff_20km = sapply(res, FUN = function(x) x$tot_active_buff_20km))

save(net_active_buff_20km_df, 
     file  = "replication_file_10_net_active_buff_20km.RData")
